<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit" :showHistoryBtn="true">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
		<om-sub :title="ms_title" :subTitle="ms_subtitle">
			<uni-list>
				<view v-for="(item, index) in workList" :key="index" >
					<uni-list-item 
					:avatar="index + 1"
					:showArrow="true"
					 @click="openWork(index)" 
					 :showClear="true"
					  @iconClear="delSub(index)">
						<view>{{ item.workName3 + "("+ (item.maxScore?item.maxScore:"未设评") +"分)"}}</view>
						<view class="text-gray text-sm padding-bottom-xs padding-top-xs">{{ item.workOutput3 }}</view>
						<view class="text-gray text-sm padding-bottom-xs padding-top-xs">{{ item.deliveryName3 }}</view>
						<view class="text-gray text-sm">{{item.bearUser3Name + ' | 计划' + item.planEnd3 + '完成'}}</view>
					</uni-list-item>
				</view>
			</uni-list>
			<view v-if="subConfigData.length" class="tui-flex align-center justify-center padding-top">
				<text class="lg text-green cuIcon-add" @click="openWork()">{{ '增加' + ms_title }}</text>
			</view>
		</om-sub>
		<om-white-space bgColor="#eee"></om-white-space>
	</om-addpage>
</template>

<script>
import { getUrl,confirmModal } from '@/static/js/common.js';
import { getFormFields,buildFormData,formValidation, tranferToEditors, changeEditor, configSelectData, hasValue,formShowLoading } from '@/static/js/formUtil.js';
import { mapState } from 'pinia';
import {useLoginUserStore} from '@/stores/login-user.js';
import urlUtil from '@/static/js/urlUtil.js';
export default {
	provide() {
		return {
			formPage: this
		};
	},
	data() {
		return buildFormData({
			menuName: '',
			id: '',
			busCode: '',
			formdata: {},
			mainConfigData: [],
			subConfigData: [],
			initValue: {
				objStr3: ''
			},
			workCacheKey: 'obj-m-proj-work-cache',
			workConfigDataCacheKey: 'obj-m-proj-work-configdata-cache',
			itemCacheKey:'obj-m-proj-item-cache',
			userCacheKey:"obj-m-proj-user-cache",
			workList: [],
			ms_title: '明细',
			ms_subtitle: '',
			scoreCode:"DD021017003"
		});
	},
	computed: {
		...mapState(useLoginUserStore,['userName', 'userId'])
	},
	watch:{
		workList:function(newValue, oldValue){
			if(newValue && newValue.length){
				if(this.$refs.autoform){
				this.$refs.autoform.formdata.objStr3 = JSON.stringify(newValue)
				}else{
					this.initValue.objStr3 = JSON.stringify(newValue)
				}
			}else{
				if(this.$refs.autoform){
					this.$refs.autoform.formdata.objStr3 = ""
				}else{
					this.initValue.objStr3 = ""
				}
			}
		}
	},
	methods: {
		formSubmit() {
			let _that = this;
			var checkRes = formValidation(this.$refs.autoform.configData, this.formdata);
			if (checkRes) {
				this.om.toast(checkRes);
			} else {
				if (!this.formdata.objStr3) {
					this.om.toast('请配置' + this.ms_title);
					return;
				}
				_that.om.formSave('torgMonthlyTargetWork/addTorgMonthlyTargetWork', _that.formdata, _that);
			}
		},
		openWork(index) {
			var checkRes = formValidation(this.$refs.autoform.configData, this.formdata);
			if (checkRes) {
				this.om.toast(checkRes);
			} else {
				uni.setStorage({
					key: this.workConfigDataCacheKey,
					data: this.subConfigData
				});
				uni.setStorage({
					key: this.workCacheKey,
					data: this.workList
				});
				var param = {
					configDataCacheKey: this.workConfigDataCacheKey,
					cachename: this.workCacheKey,
					index: index
				};
				var url = getUrl('data-info', param);
				uni.navigateTo({
					url: url
				});
			}
		},
		delSub(index){
			if(index != null) {
				this.workList.splice(index,1)
			}
		},
		initLoad(options) {
			let _that = this;
			if (!this.busCode) {
				return;
			}
			var fileId = options.fileId
			var pro1 = this.om.request('formFieldConfig/showPage', { code: this.busCode });
			// var pro1 = this.om.request('tableModel/addPage', { code: this.busCode });
			var pro2 = this.om.request('wxPosBusiAuth/isnewList', { code: this.busCode }, 'post');
			var pro3 = this.om.request('tkeyWorkList/findItemList');
			var pro4 = this.om.request('dataDict/getIntByCode',{code:_that.scoreCode})
			//多个AJAX全部完成时开始执行
			var pro5 = ""
			if(fileId){
				pro5 = _that.om.request(
				"torgMonthlyTargetWork/getInfo",
				{
					id:fileId
				},
				"post"
				)
			}
			Promise.all([pro1, pro2, pro3, pro4,pro5])
				.then(res => {
					if (res[0].succeed) {
						let data = res[0].value;
						var mainData = [
							{
								key: 'topinfo',
								editors: tranferToEditors(data.top)
							}
						];
						if (data.bodyTitle.length > 0) {
							for (var i = 0; i < data.bodyTitle.length; i++) {
								var datas = data['body' + i];
								if (data.bodyTitle[i].fieldId == 'title2') {
									_that.ms_title = data.bodyTitle[i].itemName;
									_that.subConfigData.push({
										title: data.bodyTitle[i].itemName,
										key: data.bodyTitle[i].fieldId,
										issub: true,
										editors: tranferToEditors(datas)
									});
								} else {
									mainData.push({
										title: data.bodyTitle[i].itemName,
										key: data.bodyTitle[i].fieldId,
										editors: tranferToEditors(datas)
									});
								}
							}
						}
						changeEditor(mainData[0].editors, 'zposId', 'data', configSelectData(res[1], 'id', 'posname'));
						// changeEditor(mainData[1].editors, 'item', 'data', res[2]);
						changeEditor(mainData[1].editors, "item", "linkParam", {
							namefield:"item",
							// notefield:"workOutput3",
							// extrafield:"planEnd3",
							// likefield:"workName3",
							initload:true,
							url:"tkeyWorkList/findItemList",
							cachename:_that.itemCacheKey,
							selectTitle:"历史项目名称"
						})
						changeEditor(mainData[1].editors,"userId","link","../../public/pageSearch/pageSearch")
						changeEditor(mainData[1].editors, "userId", "linkParam", {
							valuefield:"id",
							namefield:urlUtil.userPageUrl().namefield,
							searchfield:"q",
							// initload:true,
							url:urlUtil.userPageUrl().url,
							cachename:_that.userCacheKey,
							placeholder:urlUtil.userPageUrl().prompt
						})
						
						changeEditor(_that.subConfigData[0].editors, 'maxScore', 'defaultValue', res[3].value);
						changeEditor(_that.subConfigData[0].editors, 'maxScore', 'max', res[3].value);
						changeEditor(_that.subConfigData[0].editors, 'maxScore', 'prompt', "介于1~"+res[3].value+"之间");
						//赋值
						_that.$refs.autoform.configData = mainData;
						if(fileId){
							var fielArr = getFormFields(mainData)
							fielArr.push("id")
							for(var i in res[4].value.torgMonthlyTargetWork){
								if(fielArr.includes(i)){
									_that.$refs.autoform.$set(_that.$refs.autoform.formdata,i,res[4].value.torgMonthlyTargetWork[i])
									_that.$set(_that.formdata,i,res[4].value.torgMonthlyTargetWork[i])
								}
							}
							_that.$nextTick(function(){
								_that.workList = res[4].value.tkeyWork_data
							})
						}
						_that.$nextTick(function(){
							if(!_that.$refs.autoform.formdata.zpsoId){
								_that.$refs.autoform.initSelectVal("topinfo","zposId")
							}else{
								_that.$refs.autoform.initSelectIndex("topinfo","zposId")
							}
						})
					} else {
						_that.om.toast(res[0].msg);
					}
				})
				.catch(err => {
					console.log(err);
				});
		}
	},
	onLoad(options) {
		let _that = this;
		_that.menuName = options.title || '临时任务分配';
		uni.setNavigationBarTitle({
			title: _that.menuName
		});
		formShowLoading(_that)
		_that.busCode = options.code;
		_that.formdata.userId = this.userId;
		_that.initLoad(options);
		uni.removeStorage({
			key: _that.workCacheKey
		})
	},
	onShow() {
		let _that = this;
		if (_that.$refs.autoform) {
			uni.getStorage({
				key: _that.workCacheKey,
				success: function(res) {
					_that.workList = res.data;
					uni.removeStorage({
						key: _that.workCacheKey
					});
				}
			});
			uni.getStorage({
				key: _that.userCacheKey,
				success: function(res) {
					if(res.data){
						let d = res.data
						var formdata  = _that.$refs.autoform.formdata
						formdata.userId = d.id
						formdata.userName = d.username
						uni.removeStorage({
							key: _that.userCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key: _that.itemCacheKey,
				success: function(res) {
					if(res.data){
						let d = res.data
						var formdata  = _that.$refs.autoform.formdata
						if(Object.prototype.toString.call(d) =="[object Object]"){
							formdata.item = d.item
						}else{
							formdata.item = d
						}
						uni.removeStorage({
							key: _that.itemCacheKey
						});
					}
				}
			});
		}
	}
};
</script>
<style></style>
